package com.web.exception;

import com.web.pojo.vo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.concurrent.TimeoutException;

/**
 * 全局异常处理器
 * @Author: wws
 * @Date: 2021/1/26 18:00
 * describe:
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public CommonResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return CommonResult.error("不支持'" + e.getMethod() + "'请求");
    }

//
//    /**
//     * 登录时异常
//     */
//    @ExceptionHandler(UsernameNotFoundException.class)
//    public CommonResult loginException(UsernameNotFoundException e) {
//        log.error(e.getMessage(), e);
//        System.out.println("quanjuyicasdasddasd");
//        return CommonResult.error(e.getMessage());
//    }

    /**
     * 下位机超时
     */
    @ExceptionHandler(TimeoutException.class)
    public CommonResult loginException(TimeoutException e) {
        log.error(e.getMessage(), e);
        return CommonResult.error("下位机超时");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public CommonResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return CommonResult.error("运行时异常:" + e.getMessage());
    }


    /**
     * 用户无权限
     */
    @ExceptionHandler(AccessDeniedException.class)
    public CommonResult accessDeniedException(RuntimeException e) {
        log.error("用户无权限访问", e);
        return CommonResult.error("用户无权限访问");
    }
    
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.error("服务器错误，请联系管理员");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResult businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        System.out.println("业务异常+BusinessException");
        return CommonResult.error(e.getMessage());
    }
}
